package name.vaccari.matteo.tai.phonedirectory.network;

import static org.junit.Assert.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.ServerSocket;

import org.junit.Test;


public class HttpProtocolTest {

	@Test
	public void testSimpleGet() throws Exception {
		String body = "<h1>Hello world!</h1>";
		HttpProtocol httpProtocol = new HttpProtocol(new MockServlet(body));
		
		String request = "GET / HTTP/1.1\r\n" 
						+ "Host: localhost:4444\r\n"
						+ "User-Agent: Mozilla/5.0\r\n"
						;
		
		String expectedResponse = "HTTP/1.1 200 OK\r\n"
			+ "Content-Length: " + body.length() + "\r\n"
			+ "Content-Type: text/html\r\n"
			+ "\r\n"
			+ body
			;		
		ByteArrayOutputStream outputStream = anyOutputStream();
		
		httpProtocol.process(new ByteArrayInputStream(request.getBytes()), outputStream);
		
		assertEquals(expectedResponse, outputStream.toString());
	}

	@Test
	public void testParsePath() throws Exception {
		MockServlet mockServlet = new MockServlet("blabla");
		
		HttpProtocol protocol = new HttpProtocol(mockServlet);
		String request = "GET /pippo/pluto HTTP/1.1\r\n" 
			+ "Host: localhost:4444\r\n"
			+ "User-Agent: Mozilla/5.0\r\n"
			;
		protocol.process(new ByteArrayInputStream(request.getBytes()), anyOutputStream());
		
		assertEquals("/pippo/pluto", mockServlet.getLastPath());
	}

	private ByteArrayOutputStream anyOutputStream() {
		return new ByteArrayOutputStream();
	}
}
